package com.StarStudio.Service.Impl;


import com.StarStudio.DAO.*;
import com.ruoyi.common.core.Entity.*;
import com.StarStudio.Service.StatisticalDataService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.*;


@Service
public class StatisticalDataServiceImpl implements StatisticalDataService {

    @Autowired
    UserInfoDAO userInfoDAO;

    @Autowired
    PanicBuyingGoodsDAO panicBuyingGoodsDAO;

    @Autowired
    PanicBuyingCouponsDAO panicBuyingCouponsDAO;

    @Autowired
    GoodsDAO goodsDAO;

    @Autowired
    CouponsDAO couponsDAO;

    @Autowired
    OrdersDAO ordersDAO;

    @Autowired
    ExchangeDAO exchangeDAO;

    /**
     * 获取银行视角统计数据
     * @return BankStatisticalData对象
     */
    @Override
    public BankStatisticalData getBankStatisticalData() {
        BankStatisticalData bankStatisticalData = new BankStatisticalData();
        bankStatisticalData.setTotal_user_number((int)userInfoDAO.findAllRecordNumber());
        bankStatisticalData.setNew_order_number_today(ordersDAO.New_order_number_today(new Timestamp(new Date().getTime()).toString().split(" ")[0]));
        bankStatisticalData.setTotal_order_number((int)ordersDAO.findAllRecordForAdmin());
        bankStatisticalData.setToday_login_user_number(userInfoDAO.today_login_user_number(new Timestamp(new Date().getTime()).toString().split(" ")[0]));
        bankStatisticalData.setToday_purchase_user_number(userInfoDAO.today_purchase_user_number());
        bankStatisticalData.setTotal_purchase_user_number(userInfoDAO.totalPurchseUserNumber());
        bankStatisticalData.setBeans_spend_today(userInfoDAO.Beans_spend_today());
        bankStatisticalData.setBeans_spend_total(userInfoDAO.Beans_spend_total());
        bankStatisticalData.setCoupons_spend_today(userInfoDAO.Coupons_spend_today());
        bankStatisticalData.setCoupons_value_spend_today(userInfoDAO.Coupons_value_spend_today());
        bankStatisticalData.setCoupons_spend_total(userInfoDAO.Coupons_spend_total());
        bankStatisticalData.setCoupons_value_spend_total(userInfoDAO.Coupons_value_spend_total());
        List<PanicBuyingGoods> panicBuyingGoodsList = panicBuyingGoodsDAO.findByStatus(1);
        List<GoodsResult> goodsResultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(panicBuyingGoodsList)){
            for (PanicBuyingGoods panicBuyingGoods : panicBuyingGoodsList) {
                GoodsResult goodsResult = new GoodsResult();
                goodsResult.setGoods(goodsDAO.findByGoods_id(panicBuyingGoods.getGoods_id()));
                goodsResult.setPanicBuyingGoods(panicBuyingGoods);
                goodsResult.setRemainEndSeconds((int)((panicBuyingGoods.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                goodsResultList.add(goodsResult);
            }
        }
        bankStatisticalData.setGoodsResultList(goodsResultList);
        List<PanicBuyingCoupons> panicBuyingCouponsList = panicBuyingCouponsDAO.findByStatus(1);
        List<CouponsResult> couponsResultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(panicBuyingCouponsList)){
            for (PanicBuyingCoupons panicBuyingCoupons : panicBuyingCouponsList) {
                CouponsResult couponsResult = new CouponsResult();
                couponsResult.setCoupons(couponsDAO.findByCoupon_id(panicBuyingCoupons.getCoupons_id()));
                couponsResult.setPanicBuyingCoupons(panicBuyingCoupons);
                couponsResult.setRemainEndSeconds((int)((panicBuyingCoupons.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                couponsResultList.add(couponsResult);
            }
        }
        bankStatisticalData.setCouponsResultList(couponsResultList);
        //查询用户最喜爱的商品（销量最高的3个）
        List<Goods> favouriteGoods = ordersDAO.findBestSellingGoods();
        if (favouriteGoods != null && favouriteGoods.size() > 0){
            for (Goods favouriteGood : favouriteGoods) {
                Map<String,Object> param = new HashMap<>();
                //查询售出时间
                Date soldTime = ordersDAO.findGoodsSoldTime(favouriteGood.getStore_id(), favouriteGood.getGoods_id());
                param.put("soldTime",soldTime);
                //查询销量
                long totalSold = ordersDAO.findGoodsTotalSold(favouriteGood.getStore_id(),favouriteGood.getGoods_id());
                param.put("totalSold",totalSold);
                favouriteGood.setParams(param);
            }
        }
        bankStatisticalData.setFavoriteGoods(favouriteGoods);
        //查询最近售出的3个商品
        List<Goods> recentlySoldGoods = ordersDAO.findRecentlySoldGoods();
        if (recentlySoldGoods != null && recentlySoldGoods.size() > 0){
            for (Goods recentlySoldGood : recentlySoldGoods) {
                Map<String,Object> param = new HashMap<>();
                //查询售出时间
                Date soldTime = ordersDAO.findGoodsSoldTime(recentlySoldGood.getStore_id(), recentlySoldGood.getGoods_id());
                param.put("soldTime",soldTime);
                recentlySoldGood.setParams(param);
            }
        }
        bankStatisticalData.setRecentlySoldGoods(recentlySoldGoods);
        //查询用户最喜欢的优惠券（销量最高的3个）
        List<Coupons> favouriteCoupons = ordersDAO.findBestSellingCoupons();
        if (favouriteCoupons != null && favouriteCoupons.size() > 0){
            for (Coupons favouriteCoupon : favouriteCoupons) {
                Map<String,Object> param = new HashMap<>();
                //查询售出时间
                Date soldTime = ordersDAO.findCouponsSoldTime(favouriteCoupon.getCoupon_id());
                param.put("soldTime",soldTime);
                //查询销量
                long totalSold = ordersDAO.findCouponsTotalSold(favouriteCoupon.getCoupon_id());
                param.put("totalSold",totalSold);
                favouriteCoupon.setParams(param);
            }
        }
        bankStatisticalData.setFavoriteCoupons(favouriteCoupons);
        //查询最近售出的3种优惠券
        List<Coupons> recentlySoldCoupons = ordersDAO.findRecentlySoldCoupons();
        if (recentlySoldCoupons != null && recentlySoldCoupons.size() > 0){
            for (Coupons soldCoupons : recentlySoldCoupons) {
                Map<String,Object> param = new HashMap<>();
                //查询售出时间
                Date soldTime = ordersDAO.findCouponsSoldTime(soldCoupons.getCoupon_id());
                param.put("soldTime",soldTime);
                soldCoupons.setParams(param);
            }
        }
        bankStatisticalData.setRecentlySoldCoupons(recentlySoldCoupons);
        //查询所有订单中志愿者分区的统计数据
        List<Map<String, Object>> volunteerAreaData = ordersDAO.getVolunteerAreaData();
        bankStatisticalData.setVolunteerArea(volunteerAreaData);
        return bankStatisticalData;
    }

    /**
     * 获取普通商家视角统计数据
     * @return StoreStatisticalData对象
     */
    @Override
    public StoreStatisticalData getStoreStatisticalData() {
        StoreStatisticalData storeStatisticalData = new StoreStatisticalData();
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Long store_id = sysUser.getUserId();
        List<Orders> orders = ordersDAO.findOrdersByStoreIdandTime(store_id, new Timestamp(new Date().getTime()).toString().split(" ")[0]);
        int Beans_spend_in_store_today = 0;
        if (!CollectionUtils.isEmpty(orders)){
            for (Orders order : orders) {
               Beans_spend_in_store_today += goodsDAO.findGoodsPriceByGoodsId(order.getGoods_id()) * order.getNumber();
            }
        }
        storeStatisticalData.setBeans_spend_in_store_today(Beans_spend_in_store_today);
        List<Orders> ordersByStoreId = ordersDAO.findOrdersByStoreId(store_id);
        int Beans_spend_in_store_total = 0;
        if (!CollectionUtils.isEmpty(ordersByStoreId)){
            for (Orders orders1 : ordersByStoreId) {
                Beans_spend_in_store_total += goodsDAO.findGoodsPriceByGoodsId(orders1.getGoods_id()) * orders1.getNumber();
            }
        }
        storeStatisticalData.setBeans_spend_in_store_total(Beans_spend_in_store_total);
        if (orders.size() > 0){
            storeStatisticalData.setNew_order_number_today(orders.size());
        }
        if (ordersByStoreId.size() > 0){
            storeStatisticalData.setTotal_order_number(ordersByStoreId.size());
        }
        List<Exchange> exchangeListToday = exchangeDAO.findByCouponsIdAndExchangeStoreToday(sysUser.getNickName(), new Timestamp(new Date().getTime()).toString().split(" ")[0]);
        double Coupons_check_value_today = 0;
        if (!CollectionUtils.isEmpty(exchangeListToday)){
            for (Exchange exchange : exchangeListToday) {
                Coupons_check_value_today += couponsDAO.findByCoupons_item_id(exchange.getCoupons_item_id()).getMarket_price();
            }
            storeStatisticalData.setCoupons_check_number_today(exchangeListToday.size());
            storeStatisticalData.setCoupons_check_value_today(Coupons_check_value_today);
        }
        List<Exchange> exchangeList = exchangeDAO.findByCouponsIdAndExchangeStore(sysUser.getNickName());
        double Coupons_check_value_total = 0;
        if (!CollectionUtils.isEmpty(exchangeList)){
            for (Exchange exchange : exchangeList) {
                Coupons_check_value_total += couponsDAO.findByCoupons_item_id(exchange.getCoupons_item_id()).getMarket_price();
            }
        }
        if (exchangeList.size() > 0){
            storeStatisticalData.setCoupons_check_number_total(exchangeList.size());
        }
        storeStatisticalData.setCoupons_check_value_total(Coupons_check_value_total);
        List<Long> purchaseUserIdToday = ordersDAO.findPurchaseUserToday(store_id, new Timestamp(new Date().getTime()).toString().split(" ")[0]);
        if (!CollectionUtils.isEmpty(purchaseUserIdToday)){
            storeStatisticalData.setPurchase_user_number_today(purchaseUserIdToday.size());
        }
        List<Long> purchaseUserTotal = ordersDAO.findPurchaseUserTotal(store_id);
        if (!CollectionUtils.isEmpty(purchaseUserTotal)){
            storeStatisticalData.setPurchase_user_number_total(purchaseUserTotal.size());
        }
        List<PanicBuyingGoods> panicBuyingGoods = panicBuyingGoodsDAO.findPBGoodsByStatusAndStoreId(1,store_id);
        List<GoodsResult> goodsResultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(panicBuyingGoods)){
            for (PanicBuyingGoods panicBuyingGoods1 : panicBuyingGoods) {
                GoodsResult goodsResult = new GoodsResult();
                goodsResult.setGoods(goodsDAO.findByGoods_id(panicBuyingGoods1.getGoods_id()));
                goodsResult.setPanicBuyingGoods(panicBuyingGoods1);
                goodsResult.setRemainEndSeconds((int)((panicBuyingGoods1.getPanic_buying_end_time().getTime() - new Date().getTime())/1000));
                goodsResultList.add(goodsResult);
            }
        }
        storeStatisticalData.setGoodsResultList(goodsResultList);
        //查询用户最喜爱的商品（销量最高的3个）
        List<Goods> favouriteGoods = ordersDAO.findStoreBestSellingGoods(store_id);
        if (favouriteGoods != null && favouriteGoods.size() > 0){
            for (Goods favouriteGood : favouriteGoods) {
                Map<String,Object> param = new HashMap<>();
                //查询售出时间
                Date soldTime = ordersDAO.findGoodsSoldTime(store_id,favouriteGood.getGoods_id());
                param.put("soldTime",soldTime);
                //查询销量
                long totalSold = ordersDAO.findGoodsTotalSold(store_id,favouriteGood.getGoods_id());
                param.put("totalSold",totalSold);
                favouriteGood.setParams(param);
            }
        }
        storeStatisticalData.setFavoriteGoods(favouriteGoods);
        //查询最近售出的商品
        List<Goods> recentlySoldGoods = ordersDAO.findStoreRecentlySoldGoods(store_id);
        if (recentlySoldGoods != null && recentlySoldGoods.size() > 0){
            for (Goods recentlySoldGood : recentlySoldGoods) {
                Map<String,Object> param = new HashMap<>();
                //查询售出时间
                Date soldTime = ordersDAO.findGoodsSoldTime(store_id,recentlySoldGood.getGoods_id());
                param.put("soldTime",soldTime);
                recentlySoldGood.setParams(param);
            }
        }
        storeStatisticalData.setRecentlySoldGoods(recentlySoldGoods);
        //查询所有订单中志愿者分区的统计数据
        List<Map<String, Object>> volunteerAreaData = ordersDAO.getStoreVolunteerAreaData(store_id);
        storeStatisticalData.setVolunteerArea(volunteerAreaData);
        return storeStatisticalData;
    }
}
